﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Janus.Cores.Tools
{
    public static class CalendarHelper
    {
        /// <summary>
        /// 判断是否为闰年
        /// 闰年的条件是符合下面二者之一：
        /// (1)年份能被4整除，但不能被100整除；
        /// (2)年份能被400整除。
        /// </summary>
        /// <param name="year">年份</param>
        /// <returns></returns>
        public static bool IsLeap(int year)
        {
            if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取指定年份每个月的天数
        /// </summary>
        /// <param name="year">年份</param>
        /// <returns></returns>
        public static List<int> GetEachMonthDays(int year)
        {
            return new List<int>() { 31, 28 + (IsLeap(year) ? 1 : 0), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        }

        /// <summary>
        /// 获取指定日期是一周的第几天
        /// </summary>
        /// <param name="date">字符串类型的日期</param>
        /// <returns></returns>
        public static int GetDayOfWeek(string date)
        {
            int dayOfWeek = -1;
            DateTime dt = DateTime.MinValue;
            if (DateTime.TryParse(date, out dt))
            {
                dayOfWeek = GetDayOfWeek(dt);
            }
            return dayOfWeek;
        }

        /// <summary>
        /// 获取指定日期是一周的第几天
        /// </summary>
        /// <param name="date">日期类型的日期</param>
        /// <returns></returns>
        public static int GetDayOfWeek(DateTime date)
        {
            int dayOfWeek = -1;
            dayOfWeek = int.TryParse(date.DayOfWeek.ToString("d"), out dayOfWeek) ? dayOfWeek : -1;
            return dayOfWeek;
        }

        /// <summary>
        /// 获取指定月表格所需行数问题：（当前月天数 + 第一天是星期几的数值）除以七
        /// </summary>
        /// <param name="year">年份</param>
        /// <param name="month">月份</param>
        /// <returns></returns>
        public static int GetMonthRowCount(int year, int month)
        {
            List<int> lstMonth = GetEachMonthDays(year);
            double num = lstMonth[month - 1] + GetDayOfWeek(new DateTime(year, month, 1));
            return (int)Math.Ceiling(num / 7.0);
        }
    }
}
